package com.easy.controllor;

import com.easy.bean.User;
import com.easy.service.LoginService;
import com.easy.util.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginControllor {

    @Autowired
    LoginService loginService;

    @GetMapping("/captcha")
    public Object captcha() {
        return Result.success( CaptchaUtil.getCaptcha());
    }

    @PostMapping("/dologin")
    public Result login( User user,@RequestParam("captcha")String captcha,@RequestParam("key")String key){
        //验证码验证
        if(!CaptchaUtil.checkCaptcha(key,captcha)){
            return Result.fail(500,"验证码错误");
        }
        //登录
        try{
            String token = loginService.login(user);
            //删除验证码（可选）
            return Result.success("登录成功",token);
        }catch(Exception e){
            e.printStackTrace();
            return Result.fail(500,e.getMessage());
        }
        //return Result.success();
    }

    @GetMapping("/getById")
    public Result getById(HttpServletRequest request, HttpSession session){
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        System.out.println(token);
        return Result.success(loginService.getById(token));
    }
//    public Result logininfo(HttpServletRequest request, HttpSession session){
//        String token = request.getHeader("token");
//        return Result.success(loginService.getById(token));
//    }
@PostMapping("/img")
public Result imgUpload(@RequestParam("file") MultipartFile file) {
        System.out.println(file.getOriginalFilename());
    if (file == null || file.isEmpty()) {
        return Result.fail(500, "文件不能为空");
    }
    try {
        String imageUrl = loginService.imgUp(file);
        System.out.println(imageUrl);
        return Result.success("头像上传成功", imageUrl);
    } catch (Exception e) {
        e.printStackTrace();
        return Result.fail(500, "上传失败: " + e.getMessage());
    }
}


}
